package com.shu.qq.config.security;

import com.alibaba.fastjson.JSON;
import com.shu.qq.common.R;
import com.shu.qq.common.constant.Roles;
import com.shu.qq.config.security.jwt.AuthenticationService;
import com.shu.qq.config.security.jwt.JwtTokenUtil;
import com.shu.qq.data.entity.User;
import com.shu.qq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class UserSecurityService {
    @Autowired
    UserService userService;
    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;


    public R register(String account, String nickname, String password) {
        if (userService.accountIsExists(account)){
            return R.FAILED("该账号已经被注册");
        }
        User user = new User();
        user.setAccount(account);
        user.setNickname(nickname);
        //以数组形式的json保存到数据库
        String[] roles = {Roles.USER};
        String rolesStr = JSON.toJSONString(roles);
        user.setRoles(rolesStr);
        //密码加密
        String encode = passwordEncoder.encode(password);
        user.setPassword(encode);
        boolean save = userService.save(user);
        return save ? R.SUCCESS("注册成功"):R.ERROR("注册异常，稍后再试");
    }

    public R<User> login(String account, String password, HttpServletResponse response) {
        User user = authenticationService.login(account, password);
        if (user == null){
            return R.FAILED("用户名或密码错误");
        }

        String userToken = jwtTokenUtil.createUserToken(user);
        response.setHeader("Authorization", userToken);//设置请求头中的Header
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        return new R(200,"登录成功",user.privacyFilter());
    }
}
